package com.lightsh.flashlight;

import com.lightsh.light.Light;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

	private long mLastBackpress = 0;
	private ImageButton mCloseBtn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);
		mCloseBtn = (ImageButton) findViewById(R.id.closeBtn);
		testSign();
	}
	private void checkAndOpen(){
		if(!Light.isAvailable()){
			Toast.makeText(this, R.string.needMx, Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
		if(!Light.isOpen()){
			Switcher.tryOpen(this);
			LightSwitchWidget.updateAllViews(this);
		}		
	}
	

	@Override
	protected void onResume() {
		super.onResume();
		checkAndOpen();
	}
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		long currentTime = System.currentTimeMillis();
		if(currentTime - mLastBackpress < 180){
			if(Light.isOpen()){
				Switcher.tryClose(MainActivity.this);
				LightSwitchWidget.updateAllViews(MainActivity.this);
			}
		}else{
			mLastBackpress = currentTime;
			mCloseBtn.postDelayed(new Runnable() {				
				@Override
				public void run() {
					finish();
				}
			}, 180);
		}
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.closeBtn:
			if(Light.isOpen()){
				Switcher.tryClose(MainActivity.this);
				LightSwitchWidget.updateAllViews(MainActivity.this);
			}
			finish();
			break;
		case R.id.settingView:
			Intent activityIntent = new Intent(MainActivity.this, BrightnessSetActivity.class);
			activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(activityIntent);
			break;
		}
	}
	private void testSign(){
		// FIXME test ndk get app info
//		try{
//			PackageManager pm = getPackageManager();
//			PackageInfo pi = pm.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
//			
//			Log.d("MainActivity", "java hashCode = " + pi.signatures[0].hashCode());
//			Log.d("MainActivity", String.format("java sign str = %s", pi.signatures[0].toCharsString()));
//			
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		
//		String packageName = Light.getPackageName(this);
//		Log.w("MainActivity", "package name from ndk : " + packageName);
	}
}
